package com.llseven.ai.spring.llseven;

import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;


/**
 * @author ywb
 * @date 2025-04-21 19:55
 */
public class QiniuBatchDownloader {
    
    private static final Logger log = LoggerFactory.getLogger(QiniuBatchDownloader.class);
    
    private static final String ACCESS_KEY = "eEfS3HF92dudS0hqjU0gNtqw3384gq1UjlEfyRUa";
    private static final String SECRET_KEY = "J2geiXSxlSDDJzax0SMi8LkXHF9wT9MnpIv38WXw";
    private static final String BUCKET_NAME = "llseven";
    private static final String DOMAIN = "http://suwchu9pz.hn-bkt.clouddn.com";
    private static final String PREFIX = "ai/result/";
    private static final String LOCAL_DIR = "/Users/ytb/images/";
    // 设置区域华南
    private static final Configuration CONFIG = new Configuration(Region.huanan());
    
    
    public static void main(String[] args) throws Exception {
        // 初始化七牛云身份认证
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, CONFIG);
        
        // 创建本地目录
        File localDir = new File(LOCAL_DIR);
        if (!localDir.exists() && !localDir.mkdirs()) {
            log.warn("Failed to create directory: {}", localDir.getAbsolutePath());
        }

        
        // 分批拉取文件列表（最多1000个）
        String marker = null;
        FileListing fileListing;
        do {
            // 获取文件列表
            fileListing = bucketManager.listFiles(BUCKET_NAME, PREFIX, marker, 1000, null);
            
            // 下载每个文件
            for (FileInfo fileInfo : fileListing.items) {
                String key = fileInfo.key;
                // 打印文件的 key
                log.info("Key: {}", key);
                // 确保 key 是文件而不是文件夹
                if (key.endsWith("/")) {
                    log.info("Skipping directory:  {}", key);
                    // 如果是目录，则跳过
                    continue;
                }
                
                // 获取完整的下载 URL
                String downloadUrl = DOMAIN + "/" + key;
                // 打印调试信息
                log.info("downloadUrl:  {}", downloadUrl);
                // 构建本地保存路径，确保文件名被包含
                String localFilePath = LOCAL_DIR + key.replace(PREFIX, "");
                
                // 替换路径分隔符，适应不同操作系统
                localFilePath = localFilePath.replace("/", File.separator);
                
                // 确保目标路径的父目录存在
                File localFile = new File(localFilePath);
                File parentDir = localFile.getParentFile();
                // 创建父目录
                if (!parentDir.exists() && !parentDir.mkdirs()) {
                    log.warn("Failed to create directory: {}", parentDir.getAbsolutePath());
                }
                
                // 下载文件并保存
                downloadFile(downloadUrl, localFilePath);
                log.info("Downloaded:  {}", key);
            }
            
            // 更新 marker 以便下一次请求获取更多文件
            marker = fileListing.marker;
        } while (fileListing.marker != null);
        
        System.out.println("Download completed.");
    }
    
    // 下载文件并保存到指定路径
    public static void downloadFile(String fileUrl, String localFilePath) throws Exception {
        // 确保目标路径是文件，而不是目录
        File localFile = new File(localFilePath);
        
        // 如果路径是目录，而不是文件，则抛出异常
        if (localFile.isDirectory()) {
            throw new Exception("Target path is a directory, not a file: " + localFilePath);
        }
        
        // 下载文件
        URL url = new URL(fileUrl);
        try (InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(localFile)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }
}
